use std::io::Write;

use clap::Parser;
use rpassword::read_password;
use wtask_base::{error::WResult, export::log_info, logs::LogArgs, machine::{CMDArgsConfigAll, WTASK_CLI_CONFIG_FILE, get_config, load_config_from_file, machine_port, write_config_to_file}};
use wtask_file::ssh_install_machine;




#[derive(Debug, Parser, Clone)]
pub struct CMDSubConfig {
    #[command(subcommand)]
    data: CMDArgsConfigAll,

    #[command(flatten)]
    pub log_args: LogArgs,
}


impl CMDSubConfig {
    pub fn run(self) -> WResult<()> {
        let configs = match self.data {
            CMDArgsConfigAll::File(args_file) => {
                get_config(CMDArgsConfigAll::File(args_file))?
            },
            CMDArgsConfigAll::Machine(mut config_machine) => {
                config_machine.machine_port = machine_port(config_machine.machine_port, config_machine.proxy);
                log_info!("Config: {config_machine}");
                vec![config_machine]
            },
            CMDArgsConfigAll::Ssh(config_ssh) => {
                let password_func = ||{
                    print!("Password: ");
                    std::io::stdout().flush().unwrap();
                    read_password().expect("Password read error")
                };
                let config = ssh_install_machine(config_ssh, password_func)?;
                log_info!("Config: {config}");
                vec![config]
            },
            CMDArgsConfigAll::List => {
                let config_all = load_config_from_file(WTASK_CLI_CONFIG_FILE, None)?
                    .iter()
                    .enumerate()
                    .map(| (i, v) | format!("{}\t{}", i+1, v))
                    .collect::<Vec<_>>()
                    .join("\n");
                log_info!("Configs:\n#\tMachine\n{config_all}");
                return Ok(());
            }
        };
        // check, req home
        // save
        write_config_to_file(configs, WTASK_CLI_CONFIG_FILE)?;
        Ok(())
    }
}